<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>tree-table</title>
    <link rel="stylesheet" href="/components/treetable-lay/assets/layui/css/layui.css">
    <link rel="stylesheet" href="/components/treetable-lay/assets/common.css"/>
    <script src="/manage/js/app.js"></script>
    <script src='/components/treetable-lay/assets/layui/layui.js'></script>
    <style>
        input {
            height: 33px;
            width: 150px;
            line-height: 33px;
            padding: 0 7px;
            border: 1px solid #ccc;
            border-radius: 2px;
            margin-bottom: -2px;
            outline: none;
        }

        input:focus {
            border-color: #009E94;
        }
    </style>
</head>

<body>
<!-- 设置数据表格宽 -->
<div class="layui-container layui-form" style="width: 96%;margin-left: 40px">
    <br>
    <br>
    <div class="layui-input-inline">
        <select id="authorityType" lay-filter="authorityType">
            <!--  <option value='" + dices[index].code + "' pid='" + dices[index].pid + "'>" + dices[index].name + "</option>-->
        </select>
    </div>
    <div class="layui-input-inline">
        <select id="fatherPid" lay-filter="fatherPid">
            <option value=''></option>
        </select>
    </div>
    <!-- 展开/折叠 -->
    <div class="layui-btn-group">
        <button class="layui-btn layui-btn-primary" id="btn-expand">全部展开</button>
        <button class="layui-btn layui-btn-primary" id="btn-fold">全部折叠</button>
    </div>
    &nbsp;&nbsp;
    <!-- 搜索按钮 -->
    <input id="edt-search" type="text" placeholder="输入关键字"/>&nbsp;&nbsp;
    <button class="layui-btn  layui-btn-normal layui-btn-sm" id="btn-search">&nbsp;搜索&nbsp;&nbsp;</button>


    <!-- 数据表格 -->
    <table id="auth-table" class="layui-table" lay-filter="auth-table"></table>


    <script type="text/html" id="barDisable">
        {{#  if(d.url != '/api/admin/authority/{id}' && d.url != '/api/admin/authority/list' && d.method != '' ){  }}

        {{#  if(d.disable ==0 ){ }}
        <input type='checkbox' authId={{d.id}} lay-filter='disable' lay-skin='switch' lay-text='启用|禁用' checked>
        {{# }if(d.disable ==1 ){ }}
        <input type='checkbox' authId={{d.id}} lay-filter='disable' lay-skin='switch' lay-text='启用|禁用'>
        {{#  } }}

        {{#  } }}
    </script>

    <script type="text/html" id="isSign">
        {{#  if(d.url != '/api/admin/authority/{id}' && d.url != '/api/admin/authority/list' && d.method != '' ){  }}

        {{#  if(d.isSign == true){ }}
        <input type='checkbox' authId={{d.id}} lay-filter='isSign' lay-skin='switch' lay-text='需验签|不验签' checked>
        {{# }if(d.isSign == false){ }}
        <input type='checkbox' authId={{d.id}} lay-filter='isSign' lay-skin='switch' lay-text='需验签|不验签'>
        {{#  } }}

        {{#  } }}
    </script>

    <!-- 每一行的数据修改或删除  -->
    <script type="text/html" id="barState">
        {{#  if( d.method != '' ){  }}

        {{#  if(d.state ==0){ }}
        <input type='checkbox' name="stateLogin-{{d.id}}" authId={{d.id}} lay-filter='stateLogin' lay-skin='switch' lay-text='需登录|不登录'>
        <input type='checkbox' name="stateAuth-{{d.id}}" authId={{d.id}} lay-filter='stateAuth' lay-skin='switch' lay-text='需授权|不授权'>
        {{# }if(d.state ==1){ }}
        <input type='checkbox' name="stateLogin-{{d.id}}" authId={{d.id}} lay-filter='stateLogin' lay-skin='switch' lay-text='需登录|不登录' checked>
        <input type='checkbox' name="stateAuth-{{d.id}}" authId={{d.id}} lay-filter='stateAuth' lay-skin='switch' lay-text='需授权|不授权'>
        {{# }if(d.state ==2){ }}
        <input type='checkbox' name="stateLogin-{{d.id}}" authId={{d.id}} lay-filter='stateLogin' lay-skin='switch' lay-text='需登录|不登录' checked>
        <input type='checkbox' name="stateAuth-{{d.id}}" authId={{d.id}} lay-filter='stateAuth' lay-skin='switch' lay-text='需授权|不授权' checked>
        {{#  } }}

        {{#  } }}
    </script>
</div>

<script>
    // 接口
    let authorityListUrl = path + "/admin/authority/list";
    let authorityUrl = path + "/admin/authority";

    // 当前行数据
    var data = null;
    let res;

    layui.config({
        base: '../components/treetable-lay/module/' //静态资源所在路径
    }).extend({
        treetable: 'treetable-lay/treetable'
    }).use(['table', 'treetable'], function () {
        init();
        // xijiaRenderTable();       // 数据表格 - 获取表格
        xijiaEventSearch();       // 监听条件搜索
        xijiaEventSwitch();       // 监听Switch开关
    });


    function init() {
        $("#authorityType").html(Dict.getDictSelect(Enums.Base.AuthorityType, 1));
        xijiaRenderTable();
        pidSelects();
        layui.form.render();

        // 监听选择
        layui.form.on('select(authorityType)', function (data) {
            xijiaRenderTable();
            pidSelects();
            layui.form.render();
        });

        // 监听选择
        layui.form.on('select(fatherPid)', function (data) {
            xijiaRenderTable();
        });
    }


    function pidSelects() {
        // 给二级选择 拼数据
        let html = "<option value=''>" + "全部" + "</option>";
        let auths = res.data;
        let type = $("#authorityType").val();
        $.each(auths, function (index, item) {
            if (item.pid == type) {
                html += "<option value='" + item.id + "'>" + item.desc + "</option>"
            }
        });
        $("#fatherPid").html(html);
    }


    /**
     *   数据表格
     * @author ws
     * @mail  1720696548@qq.com
     * @date  2020/4/19 0019 21:43
     * @return
     */
    function xijiaRenderTable() {
        //菜单数据
        res = Ajax.get(authorityListUrl + "?" + xijiaSearchParam());
        // 渲染表格
        layer.load(2);
        //加载数据
        layui.treetable.render({
            treeColIndex: 0,             // 菜单列索引 ,加载展开图标
            treeSpid: 0,                // 顶级父id
            treeIdName: 'id',            // id 名称
            treePidName: 'pid',          // fid 名称
            treeDefaultClose: false,     // 是否默认折叠
            treeLinkage: true,           // 父级展开时是否自动展开所有子级
            elem: '#auth-table',         //table 的 div
            //url:'/menu/findAll',                         //后台接口获取数据
            //url: '../treetable-lay/json/menus.json',     //json文件获取数据
            data: res.data,                           //直接加载数据
            page: false,
            done: function () {
                //  $("table").css("width", "96%");
                layer.closeAll('loading');
            },
            cols: [
                [
                    //{field: 'pid', title: '权限类Id(方法与类/层级关系展示)'},
                    {field: 'desc', title: '权限备注信息', width: "22%"},
                    {field: 'method', title: '请求方式', width: 168},
                    {field: 'url', title: '权限url', width: "22%"},
                    {
                        field: 'type', title: '终端', width: 180, templet: function (res) {
                            return Dict.convert(Enums.Base.AuthorityType, res.type);
                        }
                    },
                    // {
                    //     field: 'state', title: '授权状态', width: 180, templet: function (res) {
                    //         if (res.method === '') {
                    //             return '';
                    //         } else {
                    //             return Dict.convert(Enums.Admin.AuthorityState, res.state);
                    //         }
                    //     }
                    // },
                    {title: '是否禁用', toolbar: '#barDisable', width: 144},
                    {title: '是否验签', toolbar: '#isSign', width: 144},
                    {title: '是否需要登录 | 是否需要授权', toolbar: '#barState', width: 240}

                ]
            ]
        });
    }


    /**
     *   条件搜索
     * @author ws
     * @mail  1720696548@qq.com
     * @date  2020/4/10 0010 0:03
     * @return
     */
    function xijiaEventSearch() {
        layui.$('#btn-expand').click(function () {
            layui.treetable.expandAll('#auth-table');
        });

        layui.$('#btn-fold').click(function () {
            layui.treetable.foldAll('#auth-table');
        });

        layui.$('#btn-search').click(function () {
            let keyword = $('#edt-search').val();
            let searchCount = 0;
            layui.$('#auth-table').next('.treeTable').find('.layui-table-body tbody tr td').each(function () {
                layui.$(this).css('background-color', 'transparent');
                let text = $(this).text();
                if (keyword !== '' && text.indexOf(keyword) >= 0) {
                    layui.$(this).css('background-color', 'rgba(250,230,160,0.5)');
                    if (searchCount === 0) {
                        layui.treetable.expandAll('#auth-table');
                        layui.$('html,body').stop(true);
                        layui.$('html,body').animate({scrollTop: $(this).offset().top - 150}, 500);
                    }
                    searchCount++;
                }
            });
            if (keyword === '') {
                layer.msg("请输入搜索内容", {icon: 5});
            } else if (searchCount === 0) {
                layer.msg("没有匹配结果", {icon: 5});
            }
        });
    }


    /**
     *  监听单选选中
     * <p>
     * switch(state) 对应 lay-filter='state'
     */
    function xijiaEventSwitch() {

        // 禁用
        layui.form.on('switch(disable)', function (data) {
            let id = data.elem.attributes['authId'].nodeValue;
            let disable = data.elem.checked ? 0 : 1;
            let result = Ajax.put(authorityUrl + "/" + id, {disable: disable});
            layui.layer.msg(result.msg)
        });

        // 是否验签
        layui.form.on('switch(isSign)', function (data) {
            let id = data.elem.attributes['authId'].nodeValue;
            let isSign = data.elem.checked;
            let result = Ajax.put(authorityUrl + "/" + id, {isSign: isSign});
            layui.layer.msg(result.msg)
        });

        // 是否需要登录
        layui.form.on('switch(stateLogin)', function (data) {
            let id = data.elem.attributes['authId'].nodeValue;
            let state = data.elem.checked ? 1 : 0;
            let result = Ajax.put(authorityUrl + "/" + id, {state: state});
            //
            let stateAuthOnswitch = $("input[name='stateAuth-" + id + "']").next().attr('class');
            if (state === 0 && stateAuthOnswitch.indexOf("layui-form-onswitch") !== -1) {
                // 刷新表格
                WindowPos.onbeforeunload();
                xijiaRenderTable();
                WindowPos.onload();
            }
            layui.layer.msg(result.msg)
        });

        // 是否需要授权
        layui.form.on('switch(stateAuth)', function (data) {
            let id = data.elem.attributes['authId'].nodeValue;
            let state = data.elem.checked ? 2 : 1;
            let result = Ajax.put(authorityUrl + "/" + id, {state: state});
            //
            let stateLoginOnswitch = $("input[name='stateLogin-" + id + "']").next().attr('class');
            if (state === 2 && stateLoginOnswitch.indexOf("layui-form-onswitch") === -1) {
                // 刷新表格
                WindowPos.onbeforeunload();
                xijiaRenderTable();
                WindowPos.onload();
            }
            layui.layer.msg(result.msg)
        });
    }


    /**
     * 搜索参数
     * @author wangsong
     * @date 2020/8/23 0023 22:53
     * @return
     * @version 1.0.1
     */
    function xijiaSearchParam() {
        let params = "";
        params += "type=" + $("#authorityType").val();
        params += "&pid=" + $("#fatherPid").val();
        return params;
    }
</script>
</body>
</html>